<?php

namespace mz\yiiext;

use Yii;
use yii\data\Pagination;
use yii\web\Request;

/**
 * 分页组件
 * Class MyPagination
 * @package mz\yiiext
 */
class MyPagination extends Pagination
{
    # 页码参数
    public $pageParam = 'p';

    # 创建url
    public function createUrl($page, $pageSize = null, $absolute = false)
    {
        $page = (int) $page;
        $pageSize = (int) $pageSize;
        if (($params = $this->params) === null) {
            $request = Yii::$app->getRequest();
            $params = $request instanceof Request ? $request->getQueryParams() : [];
        }
        if ($page > 0 || $page == 0 && $this->forcePageParam) {
            $params[$this->pageParam] = $page + 1;
        } else {
            unset($params[$this->pageParam]);
        }
        if ($pageSize <= 0) {
            $pageSize = $this->getPageSize();
        }
        if ($pageSize != $this->defaultPageSize) {
            $params[$this->pageSizeParam] = $pageSize;
        } else {
            unset($params[$this->pageSizeParam]);
        }
        $params[0] = $this->route === null ? $this->getRouteUri() : $this->route;

        $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
        if ($absolute) {
            return $urlManager->createAbsoluteUrl($params);
        }
        return $urlManager->createUrl($params);
    }

    # 获取请求路由
    public function getRouteUri()
    {
        $uri = parse_url(Yii::$app->request->getUrl());
        return isset($uri['path']) ? $uri['path'] : '';
    }
}